package com.zrm.zfcrpa.configuration.security.mobile;

import com.zrm.zfcrpa.configuration.security.MyUserDetals;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

public class SmsCodeAuthProvider implements AuthenticationProvider {

    private MyUserDetals myUserDetals;

   public void setMyUserDetals(MyUserDetals myUserDetals){
       this.myUserDetals = myUserDetals;
   }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthToken smsCodeAuthToken = (SmsCodeAuthToken) authentication;
        UserDetails user = myUserDetals.loadUserByMobile((String) smsCodeAuthToken.getPrincipal());
        if(user == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SmsCodeAuthToken result = new  SmsCodeAuthToken(user,user.getAuthorities());
        result.setDetails(smsCodeAuthToken.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthToken.class.isAssignableFrom(aClass);
    }
}
